<template>
  <div class="app-container table-app-container">
    <el-row>
      <el-col :span="4">
        <el-tree ref="tree" style="height: 460px!important;" :data="treeData" :props="defaultTreeProps" node-key="_id" @node-click="onTreeSelected" />
      </el-col>
      <el-col :span="20">
        <div class="fixed-table">
          <div class="fixed-table-actionbar">
            <TableFilter
              ref="filterForm"
              :kw="kw"
              :schema-id="schemaId"
              :inactive="inactive"
              @on-filter="searchContext"
            />
          </div>
          <PageableTable
            :key="tableKey"
            ref="myTable"
            :loading="loading"
            :data="insideTableData"
            :total="totalElements"
            :page="currentPage"
            :page-size="pageSize"
            :table-height="tableHeight"
            class="fixed-table-table"
            :multiple-selected="true"
            @page-change="onPageChange"
            @sort-change="onSortChange"
          >
            <el-table-column v-for="column in insideColumns" :key="column.key" :min-width="120" :label="column.title" :prop="column.key">
              <template slot-scope="scope">
                <column-render v-if="column.render" :render="column.render" :row="scope.row" :column="column" :show-overflow-tooltip="true" />
                <span v-else>{{ scope.row[column.key] || '-' }}</span>
              </template>
            </el-table-column>
          </PageableTable>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import TableFilter from './components/tableFilter'
import PageableTable from '@neu/biz-core/components/PageableTable'
import databind from '@neu/biz-core/mixins/databind'
import { tree as schemaTree } from '@neu/dcom-ui/api/schema'
import { pageBySchema } from '@neu/dcom-ui/api/instance'
import { deepClone } from '@neu/biz-core/utils'

export default {
  name: 'CmdbInstancePage',
  components: {
    TableFilter,
    PageableTable
  },
  // 加入混入，使表格混入更多的api操作
  mixins: [databind],
  props: {},
  data() {
    return {
      r: '',
      insideColumns: [
        { title: 'ID', key: '_id' },
        { title: '唯一标识', key: 'code' },
        { title: '名称', key: 'name' },
        { title: '模型', key: 'schemadefName' }
      ],
      defaultTreeProps: {
        children: 'children',
        label: 'name'
      },
      treeData: [],
      context: {}, // 当前选中的模型，页面的所有操作都需要在某一模型下进行
      tableKey: '', // 控制表格的渲染，防止切换模型时，表格渲染变形
      kw: '' // 模糊查询关键字
    }
  },
  computed: {
    schemaId() {
      return this.context._id
    },
    inactive() {
      return !this.context._id
    }
  },
  // 可能通过路由传递schemadef和kw两个参数
  // 如果传递schemadef参数，页面打开后，直接请求模型下所有实例
  // 如果传递kw，必须同时传递schemadef参数，否则无效
  created() {
    const schemaId = this.$route.query.schemadef
    if (this.$route.query.kw) {
      this.kw = this.$route.query.kw
    }
    // 必须先加载模型树，然后在请求具体模型下的实例
    schemaTree().then(response => {
      const treeData = response.data
        .filter(it => it.children && it.children.length > 0)
        .map(it => {
          it.children = it.children.filter(
            c => {
              const hasChildren = c.children && c.children.length > 0
              if (schemaId && hasChildren) {
                const schemaDef = c.children.find(s => s._id === schemaId)
                if (schemaDef) {
                  this.onTreeSelected(schemaDef)
                }
              }
              return hasChildren
            }
          )
          return it
        })
      this.treeData = treeData
    })
  },
  methods: {
    responseFormatter(data) {
      const formatData = data.map(it => {
        const { _id, name, code, schemadef, attrs } = it
        const mAttrs = attrs.reduce((o, item) => { o[item.key] = item.value; return o }, {})
        const d = {
          _id,
          name,
          code,
          schemadef: schemadef._id,
          schemadefName: schemadef.name,
          ...mAttrs
        }
        // 保留记录的原始值，在取消编辑时，可恢复原始值
        d.v0 = Object.freeze(deepClone(d))
        return d
      })
      return formatData
    },
    // 点击树、路由传递模型参数时，都会调用
    onTreeSelected: async function(data, node) {
      // this.$refs.tree.setCurrentKey(data._id)
      if (data.children && data.children.length > 0) return
      this.tableKey = data._id
      this.context = data
      this.r = pageBySchema(data._id)
      this.filter({ s_kw: this.kw })
    },
    searchContext(query) {
      query = { ...query }
      this.filter(query)
    }
  }
}
</script>
